package com.pharmacy.task;


import com.pharmacy.entity.Medicines;
import com.pharmacy.mapper.ExpiredDrugsMapper;
import com.pharmacy.mapper.MedicinesMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class ExpiredDrugSTask {

    @Autowired
    private MedicinesMapper medicinesMapper;

    @Autowired
    private ExpiredDrugsMapper expiredDrugsMapper;

    /**
     * 处理快期过期药物
     */

//        @Scheduled(cron = "1/5 * * * * ?")
    @Scheduled(cron = "0 0 0 * * ?")// 每天晚上12点
    @Transactional // 添加事务管理
    public void expiredDrugTask() {
        log.info("过期药物定时任务开始 {}", LocalDateTime.now());

        // 计算过期日期
        LocalDateTime expirationDate = LocalDateTime.now().plusDays(15);
        List<Medicines> list = medicinesMapper.getExpiredDrugs(expirationDate);

        for (Medicines medicines : list) {
            try {
                expiredDrugsMapper.addExpiredDrugs(medicines);
                medicinesMapper.deleteMedicines(medicines.getId());
                log.info("处理过期药物: {}", medicines.getId());
            } catch (Exception e) {
                log.error("处理药物 {} 时出错: {}", medicines.getId(), e.getMessage());
                // 这里抛出异常以触发事务回滚
                throw e;
            }
        }

        log.info("过期药物定时任务结束 {}", LocalDateTime.now());
    }
}
